package air2.totc.crypt;


import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author IDIRI
 *
 */
public class TripleDesEncoder extends SymetricalEncoder
{
	
	
	public static int MAX_KEY_LENGTH = DESedeKeySpec.DES_EDE_KEY_LEN;
	private static String ENCRYPTION_KEY_TYPE = "DESede";
	private static String ENCRYPTION_ALGORITHM = "DESede/CBC/PKCS5Padding";
	private SecretKeySpec keySpec;
	 
	public TripleDesEncoder(byte[] key) throws NoSuchAlgorithmException {
		key = Encoder.padKeyToLength(key, MAX_KEY_LENGTH);
		keySpec = new SecretKeySpec(key, ENCRYPTION_KEY_TYPE);
	}
		 
	
	/*private byte[] padKeyToLength(byte[] key, int len) {
		byte[] newKey = new byte[len];
		System.arraycopy(key, 0, newKey, 0, Math.min(key.length, len));
		return newKey;
	}*/
		 
	
	public byte[] encrypt(byte[] bOutData) throws GeneralSecurityException {
		return doCipher(bOutData, Cipher.ENCRYPT_MODE);
	}
		 
	public byte[] decrypt(byte[] bInData) throws GeneralSecurityException {
		return doCipher(bInData, Cipher.DECRYPT_MODE);
	}
		 
	private byte[] doCipher(byte[] original, int mode) throws GeneralSecurityException {
		Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
			    
		IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
		cipher.init(mode, keySpec); //, iv);
		return cipher.doFinal(original);
	}
}